/*
 * @lc app=leetcode.cn id=61 lang=java
 *
 * [61] 旋转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(k == 0 || head == null || head.next == null){
            return head;
        }
        ListNode p = head;
        int length = 1; //这里为1是因为p要走到链表的最后一个结点，不能走到空，不然没办法闭环
        while(p.next!=null){
            p = p.next;
            length++;
        }
        int number = length - k%length;
        if(k%length==0){
            return head;
        }
        p.next = head; //构成闭环
        while(number > 0){
            p = p.next;
            number--;
        }
        ListNode ans = p.next;
        p.next = null; // 断开
        return ans;
    }
}
// @lc code=end

